package com.example.springbootdemo.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class CommonUtil {
    /**
     * remove()....
     */
    private Lock lock = new ReentrantLock();

    /**
     * 判断对象是否为空
     *
     * @param o
     * @return
     */
    public static boolean isEmpty(Object o) {
        if (o == null) {
            return true;
        }
        if (o instanceof String) {
            if (o.toString().trim().equals("")) {
                return true;
            }
            if (o.toString().trim().equals("null")) {
                return true;
            }
        } else if (o instanceof List) {
            if (((List) o).size() == 0) {
                return true;
            }
        } else if (o instanceof Map) {
            if (((Map) o).size() == 0) {
                return true;
            }
        } else if (o instanceof Set) {
            if (((Set) o).size() == 0) {
                return true;
            }
        } else if (o instanceof Object[]) {
            if (((Object[]) o).length == 0) {
                return true;
            }
        } else if (o instanceof int[]) {
            if (((int[]) o).length == 0) {
                return true;
            }
        } else if (o instanceof long[]) {
            if (((long[]) o).length == 0) {
                return true;
            }
        }
        return false;
    }


    public static boolean isNotEmpty(Object o) {
        return !isEmpty(o);
    }

    /**
     * 对象组中是否存在 Empty Object
     *
     * @param os 对象组
     * @return
     */
    public static boolean isOneEmpty(Object... os) {
        for (Object o : os) {
            if (isEmpty(o)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 对象组中是否全是 Empty Object
     *
     * @param os
     * @return
     */
    public static boolean isAllEmpty(Object... os) {
        for (Object o : os) {
            if (!isEmpty(o)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 时间格式化 年月日 时分秒 毫秒
     *
     * @param time
     * @return
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
    public static String getDateTimeMsStr(Date time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(time);
    }

    /**
     * 时间格式化 年月日 时分秒
     *
     * @param time
     * @return
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public static String getDateTimeStr(Date time) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
    }

    /**
     * 年月日
     *
     * @param time
     * @return
     */
    @JsonFormat(pattern = "yyyy-MM-dd")
    public static String getDateStr(Date time) {
        return new SimpleDateFormat("yyyy-MM-dd").format(time);
    }

    /**
     * 获取request流里面的数据
     *
     * @param request
     * @return
     */
    public static String getInputStream(HttpServletRequest request) {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = request.getInputStream();
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int result = 0;
            while ((result = in.read(buffer)) != -1) {
                out.write(buffer, 0, result);
            }
            return out.toString("UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        request.getRemoteHost();
        String ipstr = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
        ipstr = getIp(ipstr);
        return ipstr;
    }

    private static String getIp(String pString) {
        String regexString = ".*(\\d{3}(\\.\\d{1,3}){3}).*";
        String regexString2 = ".*(\\d{2}(\\.\\d{1,3}){3}).*";
        String IPString = pString.replaceAll(regexString, "$1");
        if (IPString.indexOf(".") > 3)
            IPString = pString.replaceAll(regexString2, "$1");
        return IPString;
    }

    public static Set<?> remEmpty(Set<?> set) {
        set.remove("");
        set.remove("null");
        set.remove(null);
        return set;
    }

    public static Boolean getDcSuccess(String dcResult) {
        try {
            if (isEmpty(dcResult)) {
                return false;
            }
            JSONObject jsonObject = JSONObject.parseObject(dcResult);
            Boolean success = jsonObject.getJSONObject("meta").getBoolean("success");
            return success;
        } catch (Exception e) {
            return false;
        }
    }

    public static Object getDcData(String dcResult) {
        JSONObject jsonObject = JSONObject.parseObject(dcResult);
        Object json = jsonObject.get("data");
        if (json == null) {
            return new JSONObject();
        }
        return json;
    }

    public JSONObject removeDcEmptyValue(JSONObject jsonObject) {
        try {
            lock.lock();
            jsonObject.keySet().forEach(key -> {
                Object value = jsonObject.get(key);
                if (isEmpty(value)) {
                    jsonObject.remove(key);
                }
            });
        } catch (Exception e) {
        } finally {
            lock.unlock();
        }
        return jsonObject;
    }


    /** 递归删除文件 */
    public static void deleteFile(File f){
        File[] b = f.listFiles();
        for(int i =0;i<b.length;i++){
            if(b[i].isFile()){
                b[i].delete();
            }else{
                deleteFile(b[i]);
            }
        }
        f.delete();
    }

}
